import { JsonAsset, Vec3 } from "cc";
import { Engine } from "../../core/Engine";
import Logger from "../../core/utils/Logger";
import { getNetTime, getNowTime } from "../../core/utils/utils";
import { DATA_NAME, DATA_OPTION, DATA_PROPERTY, TIMER_TASK_TAG } from "../GameConstant";
import { gameRecordManager, GAME_ACCOUNT_KEY, PLAYER_STORAGE_KEY } from "../manager/GameRecordManager";
import { BaseData } from "./BaseData";
import { dataManager } from "./DataManager";
import { BELONG_TYPE } from "./MapData";

/**
 * Predefined variables
 * Name = PlayerData
 * DateTime = Sun Dec 19 2021 00:07:38 GMT+0800 (中国标准时间)
 * Author = han2007happy
 * FileBasename = PlayerData.ts
 * FileBasenameNoExtension = PlayerData
 * URL = db://assets/scripts/game/data/PlayerData.ts
 * ManualUrl = https://docs.cocos.com/creator/3.3/manual/en/
 *
 */
export class AccountData extends BaseData {
    dataName = DATA_NAME.ACCOUNT_DATA;
    // 玩家数据
    accountData: { id: number; name: string; cTime: number } | undefined; // 玩家账号
    playerRoles: { [roleId: string]: { level: number } } | undefined; // 角色数据 等级装备等等

    private gameDuringTime = 0; // 游戏持续时间

    currentRoleId!: string; // 当前选择的角色id
    protected init() {
        this.loadPlayerCacheData().then(() => {
            this._init = true;
            Engine.eventManager.emit(this.buildEventName(DATA_OPTION.INIT));
        });
    }

    async loadPlayerCacheData() {
        this.accountData = await this.getAccountData();
        const storyRoleListStr = Engine.storageManager.getItem(GAME_ACCOUNT_KEY.STORE_PLAYER_ROLES);
        if (storyRoleListStr) {
            this.playerRoles = JSON.parse(storyRoleListStr);
        }
    }

    // 账号信息
    async getAccountData() {
        const existPlayer = Engine.storageManager.getItem(GAME_ACCOUNT_KEY.STORE_PLAYER_ACCOUNT);
        if (existPlayer) {
            return JSON.parse(existPlayer);
        }
        // 新用户
        const localTime = Date.now();
        const netDate = await getNetTime();
        let netTime = localTime;
        if (netDate) {
            netTime = Date.parse(netDate);
        }
        Logger.log("AccountData netTime localTime:", localTime, netTime);
        const newPlayerData = {
            id: localTime,
            name: "测试用户",
            cTime: netTime,
        };
        gameRecordManager.setPlayerDataByKey(GAME_ACCOUNT_KEY.STORE_PLAYER_ACCOUNT, newPlayerData);
        return newPlayerData;
    }

    // 选择当前角色
    async chooseRole(roleId: string) {
        this.currentRoleId = roleId;
        await gameRecordManager.initGameData();
        if (!this.playerRoles) {
            this.playerRoles = {};
        }
        if (!this.playerRoles[roleId]) {
            // 初始化数据
            this.playerRoles[roleId] = { level: 1 };
            gameRecordManager.setPlayerDataByKey(GAME_ACCOUNT_KEY.STORE_PLAYER_ROLES, this.playerRoles);
        }

        this.initPlayerData();
    }

    // 初始化玩家数据
    private initPlayerData() {
        dataManager.dataMap.initData();
        dataManager.dataPlayer.initData();
        dataManager.dataEnemy.initData();
        // 资源增长
        Engine.timeManager.registerTimer(
            TIMER_TASK_TAG.TIMER_GAME_RESOURCE_ADD,
            1,
            0,
            () => {
                this.gameDuringTime += 1;
                if (this.gameDuringTime % 10 === 0) {
                    // 资源10s变动一次
                    dataManager.dataPlayer.preFrameAddResource(10);
                    dataManager.dataEnemy.preFrameAddResource(10);
                }

                if (this.gameDuringTime % 60 === 0) {
                    dataManager.dataPlayer.preSecondCheckKillSoldiers();
                    dataManager.dataEnemy.preSecondCheckKillSoldiers();
                }

                dataManager.dataPlayer.preFrameCheckSoldierArmy(1);
                dataManager.dataEnemy.preFrameCheckSoldierArmy(1);

                dataManager.dataMap.preFrameUpdate(1);
            },
            undefined,
            this
        );
    }
}
